//
//  JTTask.swift
//  FoundationCustom
//
//  Created by ZhouJiatao on 2019/3/3.
//  Copyright © 2019 Unknow. All rights reserved.
//

import Foundation


public class JTTask {
    public typealias TaskContent = ()->Void
    
    public enum State {
        case idle
        case doing
        case done
    }
    public private(set) var state: State = .idle
    private var content: TaskContent
    public var identifier: String?
    public init(identifier: String? = nil, content: @escaping TaskContent) {
        self.identifier = identifier
        self.content = content
    }
    
    public func run() {
        if state == .idle {
            state = .doing
            print("JTTask Run!!! identifier=\(identifier ?? "nil")")
            content()
        }
    }
    
    public func done() {
        state = .done
        print("JTTask Done!!! identifier=\(identifier ?? "nil")")
    }
    
    public func idle() {
        state = .idle
        print("JTTask Idle!!! identifier=\(identifier ?? "nil")")
    }
    
}

public extension Array where Element: JTTask {
    /// 全部任务完成
    public var allDone: Bool {
        for t in self {
            if t.state != .done {
                return false
            }
        }
        return true
    }
    
    /// 空闲任务
    public var idleItems: [JTTask] {
        var newTs: [JTTask] = self
        for t in self {
            if t.state == .idle {
                newTs.append(t)
            }
        }
        
        return newTs
    }
    
    public func runAll() {
        for t in self {
            t.run()
        }
    }
}
